package com.gao.wechat.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import net.sf.json.JSONObject;

/**
 * 模板消息
 * @author gyj
 *
 */
public class TemplateMessageUtil
{
	private static final Logger logger = LoggerFactory.getLogger(TemplateMessageUtil.class);
	
	/**
	 * 获取模板ID
	 * @param accessToken
	 * @param templateIdShort
	 * @return
	 */
	public static String getTemplateId(String accessToken,String templateIdShort) 
	{
		try {
            // 拼接请求地址
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=" + accessToken;
            // 需要提交的json数据
            String json = HttpUtil.post(requestUrl,templateIdShort);
            JSONObject jsonObject = JSONObject.fromObject(json);
            if (jsonObject == null) {
                return null;
            }
            int errorCode = jsonObject.getInt("errcode");
            if (errorCode == 0) {
                return jsonObject.getString("template_id");
            } else {
                String errorMsg = jsonObject.getString("errmsg");
                logger.error("sendMsg errcode:" + errorCode + " errmsg:" + errorMsg);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
	}
	
	/**
	 * 获取模板列表
	 * @param accessToken
	 * @param templateIdShort
	 * @return
	 * {    
 			"template_list": [{
      		"template_id": "iPk5sOIt5X_flOVKn5GrTFpncEYTojx6ddbt8WYoV5s",
      		"title": "领取奖金提醒",
      		"primary_industry": "IT科技",
      		"deputy_industry": "互联网|电子商务",
      		"content": "{ {result.DATA} }\n\n领奖金额:{ {withdrawMoney.DATA} }\n领奖  时间:{ {withdrawTime.DATA} }\n银行信息:{ {cardInfo.DATA} }\n到账时间:  { {arrivedTime.DATA} }\n{ {remark.DATA} }",
      		"example": "您已提交领奖申请\n\n领奖金额：xxxx元\n领奖时间：2013-10-10 12:22:22\n银行信息：xx银行(尾号xxxx)\n到账时间：预计xxxxxxx\n\n预计将于xxxx到达您的银行卡"
   			}]
		}
	 */
	public static JSONObject getAllPrivateTemplate(String accessToken) 
	{
		try {
            // 拼接请求地址
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=" + accessToken;
            // 需要提交的json数据
            String json = HttpUtil.get(requestUrl);
            JSONObject jsonObject = JSONObject.fromObject(json);
            if (jsonObject == null) {
                return null;
            }
           return jsonObject;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
	}
	
	/**
	 * {
           "touser":"OPENID",
           "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
           "url":"http://weixin.qq.com/download",  
           "miniprogram":{
             "appid":"xiaochengxuappid12345",
             "pagepath":"index?foo=bar"
           },          
           "data":{
                   "first": {
                       "value":"恭喜你购买成功！",
                       "color":"#173177"
                   },
                   "keyword1":{
                       "value":"巧克力",
                       "color":"#173177"
                   },
                   "keyword2": {
                       "value":"39.8元",
                       "color":"#173177"
                   },
                   "keyword3": {
                       "value":"2014年9月22日",
                       "color":"#173177"
                   },
                   "remark":{
                       "value":"欢迎再次购买！",
                       "color":"#173177"
                   }
           }
       }
	 * 发送消息给用户
	 * @param accessToken
	 * @param msg
	 * @return
	 */
	public static boolean sendTemplateMsg(String accessToken, String msg) 
	{
		try {
            // 拼接请求地址
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
            // 需要提交的json数据
            String json = HttpUtil.post(requestUrl,msg);
            JSONObject jsonObject = JSONObject.fromObject(json);
            if (jsonObject == null) {
                return false;
            }
            int errorCode = jsonObject.getInt("errcode");
            if (errorCode == 0) {
                return true;
            } else {
                String errorMsg = jsonObject.getString("errmsg");
                logger.error("sendMsg errcode:" + errorCode + " errmsg:" + errorMsg);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return false;
	}
	
	public static String getAccessToken(String appId, String secret) 
	{
		try 
		{
			String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appId +"&secret="+ secret;
		    String json = HttpUtil.get(requestUrl);
		    JSONObject jsonObject = JSONObject.fromObject(json);
		    if (jsonObject == null)
		    {
		    	logger.error("获取accessToken失败");
                return null;
            }
		    String access_token = jsonObject.getString("access_token");
		    return access_token;
		}catch(Exception ex) 
		{
			logger.error(ex.getMessage(), ex);
		}
		return null;
	}
}
